/*
 *  clb_program.c
 *  DeferredLighting
 *
 *  Created by Holmes Futrell on 2/9/11.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "clb_program.h"
#include "clb_error.h"

#include <stdio.h>
#include <stdlib.h>

char *clb_stringWithPath(const char *path) {
	
	FILE *f = fopen(path, "r");
	
	if (!f) {
		printf("warning: could not open '%s'!\n", path);
		return NULL;
	}
	
	fseek(f, 0, SEEK_END);
	int file_length = ftell(f);
	rewind(f);
	
	char *string = (char *)malloc(file_length + 1);
	char *s = string;
	while ( !feof(f) && !ferror(f) ) {
		int read = fread(s, 1, 2048, f);
		s += read;
	}
	s[0] = '\0'; /* make sure string ends with NULL character */
	
	fclose(f);
	
	return string;
	
}

int	buid_succeeded(cl_program p, cl_device_id d) {
	
	cl_build_status build_status;
	size_t size;
	
	clb_check_error( clGetProgramBuildInfo( p, d, CL_PROGRAM_BUILD_STATUS, sizeof(build_status), &build_status, &size ),
					"clGetProgramBuildInfo");

	
	return build_status == CL_BUILD_SUCCESS;
	
}

void print_build_info(const cl_program p, const cl_device_id d) {
	
	cl_build_status build_status;
	char build_options[2048];
	char build_log[2048*1024];
	size_t size;
	
	clb_check_error( clGetProgramBuildInfo( p, d, CL_PROGRAM_BUILD_STATUS, sizeof(build_status), &build_status, &size ),
					"clGetProgramBuildInfo");
	
	printf("CL_PROGRAM_BUILD_STATUS: ");
	switch (build_status) {
		case CL_BUILD_NONE:
			printf("CL_BUILD_NONE");
			break;
		case CL_BUILD_ERROR:
			printf("CL_BUILD_ERROR");
			break;
		case CL_BUILD_SUCCESS:
			printf("CL_BUILD_SUCCESS");
			break;
		case CL_BUILD_IN_PROGRESS:
			printf("CL_BUILD_IN_PROGRESS");
			break;
		default:
			printf("[UNKNOWN]");
			break;
	}
	printf("\n");
	
	clb_check_error( clGetProgramBuildInfo( p, d, CL_PROGRAM_BUILD_OPTIONS, sizeof(build_options), &build_options, &size ), "clGetProgramBuildInfo" );
	printf("CL_PROGRAM_BUILD_OPTIONS: %s\n", build_options);
	
	clb_check_error( clGetProgramBuildInfo( p, d, CL_PROGRAM_BUILD_LOG, sizeof(build_log), &build_log, &size ), "clGetProgramBuildInfo" );
	printf("CL_PROGRAM_BUILD_LOG: %s\n", build_log);
	
	
}